﻿using System;
using System.Collections.Generic;
using Common.Logging;
using Microsoft.Practices.Unity.InterceptionExtension;
using Common.Object;

namespace Common.InterceptionBehavior
{
    public class LoggingInterceptionBehavior : IInterceptionBehavior
    {

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var methodInfo = getNext();
            LoggerHelper.Log(input.MethodBase.ReflectedType, LoggerLevel.Debug, string.Format("{0}=>{1}", input.MethodBase.Name, input.MethodBase.GetParameters().ToString(input)));
            var result = methodInfo.Invoke(input, getNext);
            if (result.Exception != null) LoggerHelper.Log(input.MethodBase.ReflectedType, LoggerLevel.Fatal, string.Format("\r\n======[Exception]======\r\n{0}.{1}\r\n{2}\r\n", input.MethodBase.ReflectedType, result.Exception.Message, result.Exception.StackTrace));
            LoggerHelper.Log(input.MethodBase.ReflectedType, LoggerLevel.Debug, string.Format("{0}<={1}", input.MethodBase.Name, (result.ReturnValue == null) ? "null" : result.ReturnValue.ToString()));
            return result;
        }
        public bool WillExecute
        {
            get { return true; }
        }

    }
}
